#include <string>
#include <iostream>
#include <map>
#include <list>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <cstring>
#include <errno.h>

/* uint32_t */
#include <stdint.h>
#include <sys/time.h>
#include <assert.h>
#include <fcntl.h>

#define CPPCGILOG(risk) COMPACT_CGI_LOG_ ## risk
#define COMPACT_CGI_LOG_INFO LogMessage("I", \
			__FUNCTION__, __LINE__).stream()

#define COMPACT_CGI_LOG_ERROR LogMessage("E", \
			__FUNCTION__, __LINE__).stream()
using namespace std;

static string func_ = "undefined";
static unsigned int cgitag_ = 0;

string GetFormatTime()
{
	time_t rawtime;
	struct tm * timeinfo;
	struct timeval now_u;
	char buffer[64];
	char bufferS[64];
	time(&rawtime);
	timeinfo = localtime(&rawtime);
	strftime(buffer, 64, "%Y-%m-%d %H:%M:%S", timeinfo);
	gettimeofday(&now_u, NULL);
	sprintf(bufferS, "%s.%d", buffer, (int)now_u.tv_usec);
	return bufferS;
}

class LogMessage
{
public:

	LogMessage(const char* mask, const char* file, int line)
	{
		fileobj.open("cppcgi.log", ios::app);
		fileobj << mask << " "
				<< GetFormatTime() << " " << func_ << "("
				<< cgitag_ << ") " << file << ":" << line << " |";
	}
	~LogMessage()
	{
		fileobj.close();
	}
	ofstream& stream() {
		return fileobj;
	}
private:
	ofstream fileobj;
};

void Hello(const string& ddg)
{
	CPPCGILOG(INFO) << ddg << "Hello" << endl;
}

int main(int argc, char* argv[])
{
	func_ = "dap.cgi";
	cgitag_ = 20;
	Hello("fd23");
    CPPCGILOG(INFO) << "foo.com" << endl;
    CPPCGILOG(ERROR) << "foo.com" << endl;
    return 0;
}
